import 'dart:convert';

import 'package:bot_toast/bot_toast.dart';
import 'package:bruno/bruno.dart';
import 'package:file_picker/file_picker.dart';

// import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get_state_manager/src/simple/get_controllers.dart';
import 'package:image_pickers/image_pickers.dart';

// import 'package:image_pickers/image_pickers.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'dart:io';
import 'package:dio/dio.dart';
import 'package:get/route_manager.dart';

import '../../../common/colors.dart';
import '../../../services/address.dart';
import '../../../services/dio_manager.dart';
import 'published_project_model.dart';

class PublishedProjectController extends GetxController {
  int project_id = 0;
  double intensity = 0.0;
  bool isShowSlider = false;
  var chargename = "请选择";
  var chargpositid = -1;

  var activenames = [];
  var activearraids = [];
  var activestrings = "请选择";

  var visibilityName = '项目可见';
  var visibilityId;

  bool isProjectOpen = true;

  List<BrnCommonActionSheetItem> actions = [];

  TextEditingController editingController = TextEditingController();

  TextEditingController editingController1 = TextEditingController();


  String login_uid = "";

  String start_time = "2022-11-11";
  String ended_time = "2022-12-12";

  var startarray = [2022, 11, 11];
  var endedarray = [2022, 12, 12];

  List<String> missionnames = [];

  void getInitData() async {
    print("getInitData==print>>");
    SharedPreferences prefs = await SharedPreferences.getInstance();
    login_uid = prefs.getInt("uid").toString();
    print("login_uid==print>>${login_uid}");
    DateTime dateTime = DateTime.now();
    start_time = dateTime.toString().substring(0, 10);
    ended_time = dateTime.toString().substring(0, 10);
    print("start_time==print>>${start_time}");
    print("ended_time==print>>${ended_time}");
  }

  /// 获取我的项目详情数据
  requestProjectDetails() async {
    var json = await DioManager()
        .kkRequest(Address.projectInfo + project_id.toString(), method: 'get');
    if (json["errcode"] == 0) {
      ProjectDetailsModel projectDetailsModel =
          ProjectDetailsModel.fromJson(json["data"]);
      editingController.text = projectDetailsModel.name.toString();
      editingController1.text = projectDetailsModel.description.toString();
      List<TagName>? userName = projectDetailsModel.userName;
      activestrings = "";
      activearraids = [];
      userName!.forEach((element) {
        activearraids.add(element.id);
        activestrings += element.name!;
        activestrings += ",";
      });
      userName.isEmpty?'':chargename = userName[0].name!;
      userName.isEmpty?'': chargpositid = userName[0].id!;

      start_time = projectDetailsModel.dateStart.toString();
      ended_time = projectDetailsModel.dateEnd.toString();
      if(projectDetailsModel.state=='off_track'){
        isProjectOpen = false;
      }else{
        isProjectOpen = true;
      }
      intensity = (projectDetailsModel.progress! / 100) * 1.0;
      isShowSlider = true;
      if (start_time.isNotEmpty) {
        var startstrings = start_time.split("-");
        startarray = [];
        startstrings.forEach((element) {
          startarray.add(int.parse(element));
        });
      }

      if (ended_time.isNotEmpty) {
        var endstrings = ended_time.split("-");
        endedarray = [];
        endstrings.forEach((element) {
          endedarray.add(int.parse(element));
        });
      }

      update();
    }
    update();
  }

  /// 选择项目可见
  tapClickVisibility()async{
   var data = await Get.bottomSheet(
      Container(
        color: Colors.yellow,
        height: 91,
        child: ListView.builder(itemBuilder: (BuildContext context, int index) {
          return GestureDetector(
            onTap: (){
              Get.back(result: index==0?'followers':'employees');
            },
            child: Column(
              children: [
                Container(
                  padding: EdgeInsets.only(left: 10),
                  color: Colors.white,
                  alignment: Alignment.centerLeft,
                  height: 45,
                  child: index==0?Text('参与人员'):Text('所有人员'),
                ),
                Container(height: 0.5,color: AppColor.lineColor,)
              ],
            ),
          );
        },itemCount: 2,),
      )
    );
   if(data!=null){
     if(data == 'followers'){
       visibilityName = '参与人员';
     }else{
       visibilityName = '所有人员';
     }
     visibilityId = data;
   }
   update();
  }


  /// 点击上传附件
  /// 点击附件icon
  var listFilePaths = [];
  var fileName = '';
  tapClickAccessory(){
    // actions.clear();
    showModalBottomSheet(
        context: Get.overlayContext!,
        backgroundColor: Colors.transparent,
        builder: (BuildContext context) {
          return BrnCommonActionSheet(
            title: "",
            actions: actions,
            clickCallBack: (
                int index,
                BrnCommonActionSheetItem actionEle,
                )async {
              if (index == 0) {
                ImagePickers.openCamera(
                    cropConfig: CropConfig(
                        enableCrop: false,
                        width: 2,
                        height: 3))
                    .then((Media? media) {
                  // _listImagePaths.clear();
                  if (media != null) {

                    var fileParams = {
                      'name':'${media.path}',
                      'path':'${media.path}',
                    };
                    listFilePaths.clear();
                    fileName = '${media.path}';
                    listFilePaths.add(fileParams);

                    print(listFilePaths);
                  }
                  update();
                });
              }
              if (index == 1) {
                ImagePickers.openCamera(
                    cameraMimeType:
                    CameraMimeType.video)
                    .then((media) {
                  // listFilePaths.clear();
                  if (media != null) {
                    print(media.path);
                    var fileParams = {
                      'name':'${media.path}',
                      'path':'${media.path}',
                    };
                    listFilePaths.clear();
                    fileName = '${media.path}';
                    listFilePaths.add(fileParams);
                  }
                  update();
                });
              }
              if (index == 2) {
                try {
                  ImagePickers.pickerPaths(
                    galleryMode: GalleryMode.image,
                    showGif: false,
                    selectCount: 1,
                    showCamera: false,
                    cropConfig: CropConfig(enableCrop: true, height: 1, width: 1),
                    compressSize: 300,
                    uiConfig: UIConfig(
                      uiThemeColor: AppColor.themeColor,
                    ),
                  ).then((value) {
                    var fileParams = {
                      'name':'${value[0].path}',
                      'path':'${value[0].path}',
                    };
                    listFilePaths.clear();
                    fileName = '${value[0].path}';
                    listFilePaths.add(fileParams);
                    update();
                  });
                  if (listFilePaths.length > 0) {
                    listFilePaths.forEach((media) {
                      print(media.path.toString());
                    });
                  }
                  update();
                } on PlatformException {}
              }
              if(index == 3){
                //往下开始用filepick提供的方法
                FilePickerResult? result = await FilePicker.platform.pickFiles(
                  type: FileType.any,
                  // allowedExtensions: ['text'],    //筛选文件类型
                );
                //这就用完了，下面就赋值了
                if (result != null) {
                  // listFilePaths.clear();
                  PlatformFile file = result.files.first;
                  print(result.files.first.path);
                  var fileParams = {
                    'name':'${file.name}',
                    'path':'${file.path}',
                  };
                  listFilePaths.clear();
                  listFilePaths.add(fileParams);

                  // listFilePaths.add(file.path);
                  fileName = result.files.first.name;
                  update();
                } else {
                  // User canceled the picker
                }
              }
              // String title = actionEle.title;
              // BrnToast.show("title: $title, index: $index", context);
            },
          );
        });
    update();
  }


  /// 是否打开事件
  tapClickIsOpen()async{

    isProjectOpen =! isProjectOpen;

    var params ;
    if(isProjectOpen==true){
      params = {
        'project_id':project_id,
        'state':'on_track',
      };
    }else{
      params = {
        'project_id':project_id,
        'state':'off_track',
      };
    }

    var json = await DioManager().kkRequest(Address.projectProjectState,bodyParams: params);

    BotToast.showText(text: json['message']);

    update();

  }


  ///删除任务
  requestDataDelete() async {
    Map<String, dynamic> hashmap = {};
    hashmap['project_id'] = project_id;
    var formData = FormData.fromMap(hashmap);
    var json = await DioManager().kkRequest(Address.projectUnlink,
        bodyParams: formData, isShowLoad: true);
    if (json['errmsg'] == 'ok') {
      Get.back();
      Get.back(result: 'refresh');
    }
    BotToast.showText(text: json['message']);
  }

  /// 发送请求
  requestDataWithPublish() async {
    Map<String, dynamic> hashmap = {};
    hashmap['name'] = editingController.text;
    hashmap['description'] = editingController1.text;
    hashmap['manager_id'] = chargpositid > 0 ? chargpositid : login_uid;
    hashmap['start_time'] = '$start_time';
    hashmap['end_time'] = '$ended_time';
    hashmap['visibility'] = visibilityId;

    if(listFilePaths.isNotEmpty){
      MultipartFile multipartFile = MultipartFile.fromFileSync(
        '${listFilePaths[0]['path']}',
        filename: '${listFilePaths[0]['name']}',
      );
      hashmap['file'] = multipartFile;
    }

    // hashmap['tags'] = '1';
    if (project_id > 0) {
      hashmap['project_id'] = project_id;
    }
    if (activearraids.isNotEmpty) {
      var activeids='';
      for (var element in activearraids) {
        activeids += element.toString();
        activeids += ",";
      }
      hashmap['user_ids'] = activeids;
    }
    var json = await DioManager().kkRequestBody(Address.projectCreate,
        params: hashmap, isShowLoad: true);
    if (json['errmsg'] == 'ok') {
      Get.back(result: 'refresh');
    }
    BotToast.showText(text: json['message']);
  }

  /// 刷新滑动组件
  refreshSlider(double value) {
    intensity = value;
    update();
  }



  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
    actions.add(BrnCommonActionSheetItem(
      '拍照',
      actionStyle: BrnCommonActionSheetItemStyle.normal,
    ));
    actions.add(BrnCommonActionSheetItem(
      '录视频',
      actionStyle: BrnCommonActionSheetItemStyle.normal,
    ));
    actions.add(BrnCommonActionSheetItem(
      '相册',
      actionStyle: BrnCommonActionSheetItemStyle.normal,
    ));
    actions.add(BrnCommonActionSheetItem(
      '文件',
      actionStyle: BrnCommonActionSheetItemStyle.normal,
    ));

    getInitData();
    project_id = Get.arguments;
    if (project_id > 0) {
      requestProjectDetails();
    }
  }
}
